package controllers

import (
	"encoding/json"
	"strconv"
	"supershare/backend/middleware"
	"supershare/backend/models"
	"time"

	"github.com/beego/beego/v2/server/web"
)

// StoreUpdateRequest 门店更新请求结构
type StoreUpdateRequest struct {
	Name          string  `json:"name"`
	Logo          string  `json:"logo"`
	Address       string  `json:"address"`
	Latitude      float64 `json:"latitude"`
	Longitude     float64 `json:"longitude"`
	Phone         string  `json:"phone"`
	Description   string  `json:"description"`
	Notice        string  `json:"notice"`
	BusinessHours string  `json:"business_hours"`
	ContactPerson string  `json:"contact_person"`
	Facilities    string  `json:"facilities"`
	Images        string  `json:"images"`
	Banner        string  `json:"banner"`
	Status        int8    `json:"status"`
	CityId        int64   `json:"city_id"`
	VenueTypes    string  `json:"venue_types"`
	SortOrder     int     `json:"sort_order"`
	IsHot         int8    `json:"is_hot"`
	FranchiseId   int64   `json:"franchise_id"`
}

// StoreController 门店管理控制器
type StoreController struct {
	web.Controller
}

// StoreListRequest 门店列表请求参数
type StoreListRequest struct {
	Page        int    `json:"page" form:"page"`
	PageSize    int    `json:"pageSize" form:"pageSize"`
	Name        string `json:"name" form:"name"`
	Status      int8   `json:"status" form:"status"`
	FranchiseId int64  `json:"franchise_id" form:"franchise_id"`
	CityId      int64  `json:"city_id" form:"city_id"`
	IsHot       int8   `json:"is_hot" form:"is_hot"`
}

// StoreCreateRequest 创建门店请求参数
type StoreCreateRequest struct {
	Name          string  `json:"name"`
	Logo          string  `json:"logo"`
	Address       string  `json:"address"`
	Latitude      float64 `json:"latitude"`
	Longitude     float64 `json:"longitude"`
	Phone         string  `json:"phone"`
	Description   string  `json:"description"`
	Notice        string  `json:"notice"`
	BusinessHours string  `json:"business_hours"`
	ContactPerson string  `json:"contact_person"`
	Facilities    string  `json:"facilities"`
	Images        string  `json:"images"`
	Status        int8    `json:"status"`
	FranchiseId   int64   `json:"franchise_id"`
	CityId        int64   `json:"city_id"`
	VenueTypes    string  `json:"venue_types"` // 场地类型，JSON格式存储
	SortOrder     int     `json:"sort_order"`
	IsHot         int8    `json:"is_hot"`
}

// Get 获取门店详情
func (c *StoreController) GetOne() {
	// 获取门店ID
	id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
	if id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的门店ID",
		}
		c.ServeJSON()
		return
	}

	// 获取当前管理员
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取门店信息
	store, err := models.GetStoreById(id)
	if err != nil || store == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "门店不存在",
		}
		c.ServeJSON()
		return
	}

	// 检查加盟商权限
	if !models.CheckFranchisePermission(admin.FranchiseId, store.FranchiseId) {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权访问该门店",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取门店详情成功",
		"data":    store,
	}
	c.ServeJSON()
}

// List 获取门店列表
func (c *StoreController) List() {
	// 获取请求参数
	page, _ := strconv.Atoi(c.GetString("page"))
	if page <= 0 {
		page = 1
	}

	pageSize, _ := strconv.Atoi(c.GetString("pageSize"))
	if pageSize <= 0 || pageSize > 100 {
		pageSize = 10
	}

	name := c.GetString("name")
	status, _ := c.GetInt8("status", -1)
	franchiseId, _ := c.GetInt64("franchise_id", 0)
	cityId, _ := c.GetInt64("city_id", 0)
	isHot, _ := c.GetInt8("is_hot", -1)

	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 构建过滤条件
	filters := make(map[string]interface{})
	if name != "" {
		filters["name"] = name
	}
	if status >= 0 {
		filters["status"] = int8(status)
	}
	if franchiseId > 0 {
		filters["franchise_id"] = franchiseId
	}
	if cityId > 0 {
		filters["city_id"] = cityId
	}
	if isHot >= 0 {
		filters["is_hot"] = int8(isHot)
	}

	// 查询门店列表
	stores, total, err := models.GetStoreList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取门店列表失败",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取门店列表成功",
		"data": map[string]interface{}{
			"list":  stores,
			"total": total,
		},
	}
	c.ServeJSON()
}

// Create 创建门店
func (c *StoreController) Create() {
	// 解析请求参数
	var req StoreCreateRequest
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 创建门店
	store := &models.Store{
		Name:          req.Name,
		Logo:          req.Logo,
		Address:       req.Address,
		Latitude:      req.Latitude,
		Longitude:     req.Longitude,
		Phone:         req.Phone,
		Description:   req.Description,
		Notice:        req.Notice,
		BusinessHours: req.BusinessHours,
		ContactPerson: req.ContactPerson,
		Facilities:    req.Facilities,
		Images:        req.Images,
		Status:        req.Status,
		CityId:        req.CityId,
		VenueTypes:    req.VenueTypes,
		SortOrder:     req.SortOrder,
		IsHot:         req.IsHot,
	}
	if admin.FranchiseId > 0 {
		store.FranchiseId = admin.FranchiseId
	}
	// 设置创建者信息
	store.CreatedBy = admin.Username
	store.UpdatedBy = admin.Username
	store.BeforeInsert()
	// 保存到数据库
	id, err := models.CreateStore(store)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建门店失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "创建门店成功",
		"data": map[string]interface{}{
			"id": id,
		},
	}
	c.ServeJSON()
}

// Update 更新门店
func (c *StoreController) Update() {
	// 获取门店ID
	id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
	if id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的门店ID",
		}
		c.ServeJSON()
		return
	}

	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 查询现有门店
	store, err := models.GetStoreById(id)
	if err != nil || store == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "门店不存在",
		}
		c.ServeJSON()
		return
	}

	// 检查加盟商权限
	if !models.CheckFranchisePermission(admin.FranchiseId, store.FranchiseId) {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权修改该门店",
		}
		c.ServeJSON()
		return
	}

	// 解析请求参数
	var req StoreUpdateRequest
	err = json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 更新门店信息
	store.Name = req.Name
	store.Logo = req.Logo
	store.Address = req.Address
	store.Latitude = req.Latitude
	store.Longitude = req.Longitude
	store.Phone = req.Phone
	store.Description = req.Description
	store.Notice = req.Notice
	store.BusinessHours = req.BusinessHours
	store.ContactPerson = req.ContactPerson
	store.Facilities = req.Facilities
	store.Images = req.Images
	store.Banner = req.Banner
	store.Status = req.Status
	store.CityId = req.CityId
	store.VenueTypes = req.VenueTypes
	store.SortOrder = req.SortOrder
	store.IsHot = req.IsHot

	// 不允许更改加盟商ID，确保维持原始加盟商ID
	// store.FranchiseId = req.FranchiseId

	// 设置更新者信息
	store.UpdatedBy = admin.Username
	store.UpdatedAt = time.Now().Unix()

	// 保存到数据库
	err = models.UpdateStore(store)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新门店失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "更新门店成功",
	}
	c.ServeJSON()
}

// Delete 删除门店
func (c *StoreController) Delete() {
	// 获取门店ID
	id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
	if id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的门店ID",
		}
		c.ServeJSON()
		return
	}

	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 查询现有门店
	store, err := models.GetStoreById(id)
	if err != nil || store == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "门店不存在",
		}
		c.ServeJSON()
		return
	}

	// 检查加盟商权限
	if !models.CheckFranchisePermission(admin.FranchiseId, store.FranchiseId) {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权删除该门店",
		}
		c.ServeJSON()
		return
	}

	// 删除门店
	err = models.DeleteStore(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "删除门店失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "删除门店成功",
	}
	c.ServeJSON()
}
